import 'package:aitao_flutter/common_ui/back_nav.dart';
import 'package:aitao_flutter/model/gift_list_model.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/text_style.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../request/api.dart';
import '../../request/requestManager.dart';

class GiftListPage extends StatefulWidget {
  const GiftListPage({super.key});

  @override
  State<GiftListPage> createState() => _GiftListPageState();
}

class _GiftListPageState extends State<GiftListPage> {
  int userId = 0;
  GiftListModel? giftListModel;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: BackNavigation(title: 'TA收到的礼物'),
        body: Container(
            padding: EdgeInsetsStyle.edgeInsets(20, 30),
            child: GridView.builder(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                //设置横向间距
                crossAxisCount: 4,
                crossAxisSpacing: 18,
                childAspectRatio: 0.5,
                //设置主轴间距
                mainAxisSpacing: 10,
              ),
              itemCount: giftListModel?.list?.length ?? 0,
              itemBuilder: (context, index) {
                return _giftItemWidget(index);
              },
            )));
  }

  Widget _giftItemWidget(int index) {
    GiftItem item = giftListModel!.list![index];
    return Column(
      children: [
        Image.network(
          SpUtil.getImageUrl(item.img ?? ''),
          width: 70.w,
          height: 70.w,
        ),
        Box.vBox3,
        Text(
          item.name ?? '',
          style: Styles.normalText_14,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        Text(
          item.price.toString(),
          style: Styles.greyText_12,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        Box.vBox3,
        Text(
          'X${item.total ?? ''}',
          style: Styles.mainText_12,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    userId = int.parse(Get.parameters['userId'].toString());
    if (userId != 0) {
      getGiftListData();
    }
  }

  void getGiftListData() async {
    var result = await RequestManager()
        .post(API.userGiftList, params: {'user_id': userId});
    if (result != null && result['code'] == 0) {
      setState(() {
        giftListModel = GiftListModel.fromJson(result['data']);
      });
    }
  }
}
